'use strict';

const BaseService = require('./base');
const {Wechatpay, Formatter, Rsa, AesGcm} = require('wechatpay-axios-plugin');
const { wxpayConfig} = require('../../config/cert/wxpay.config');
const wxpay = new Wechatpay(wxpayConfig);


class WechatPayService extends BaseService {

    /**
     * JSAPI下单
     * @param {*} order 
     * @param {*} openid 
     * @param {*} description 
     * @param {*} notify_url 
     * @returns 
     */
    async jsapi(order, openid, description = '', notify_url = 'https://dmodev.cn') {
        const res = await wxpay.v3.pay.transactions.jsapi
            .post({
                "mchid": wxpayConfig.mchid,
                "out_trade_no": order.order_no,
                "appid": wxpayConfig.appid,
                "description": description,
                "notify_url": notify_url,
                "amount": {
                    "total": order.total_amount * 100,
                    "currency": "CNY"
                },
                "payer": {
                    "openid": openid
                }
            })
            .then(res => {
                return res.data;
            })
            .catch(({response: {status, statusText, data}}) => {
                return data;
            })
        if ('code' in res) {
            this.ctx.helper.commonErr(res.message);
        }
        if (!('prepay_id' in res && res.prepay_id.length > 0)) {
            this.ctx.helper.commonErr('预付款失败');
        }
        return res.prepay_id;
    }

    /**
     * V3签名
     * @param {*} prepay_id 
     * @returns 
     */
    async sign(prepay_id) {
        const params = {
            appId: wxpayConfig.appid,
            timeStamp: `${Formatter.timestamp()}`,
            nonceStr: Formatter.nonce(),
            package: `prepay_id=${prepay_id}`,
            signType: 'RSA',
        }
        params.paySign = Rsa.sign(Formatter.joinedByLineFeed(
            params.appId, params.timeStamp, params.nonceStr, params.package
        ), wxpayConfig.privateKey)

        return params;
    }

    /**
     * 查询订单 -- 订单号
     * @param {*} out_trade_no 
     * @returns 
     */
    async orderqueryByOutTradeNo(out_trade_no) {
        const res = await wxpay.v3.pay.transactions.outTradeNo['{out_trade_no}']
            .get({
                params: {
                    mchid: wxpayConfig.mchid
                }, 
                out_trade_no: out_trade_no
            })
            .then(res => {
                return res.data;
            })
            .catch(({response: {status, statusText, data}}) => {
                return data;
            })
        
        if ('code' in res) {
            this.ctx.helper.commonErr(res.message);
        }
        if (!('trade_state' in res && res.trade_state == 'SUCCESS')) {
            console.log(res);
            this.ctx.helper.commonErr('支付成功');
        }
        //处理订单业务
        return res;
    }

}

module.exports = WechatPayService;